#include "stdafx.h"
#include "VSCtxMenuFixApp.h"

static WCHAR g_szRegSubKey[] = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
static WCHAR g_szRegValueName[] = L"VSCtxMenuFixApp";

static LPWSTR GetAutorunFileName();
static LPWSTR GetQuotedString(LPWSTR);

BOOL CMyAppStartup::DoesAppStartWhenWindowsStarts()
{
    CMyBuffer<WCHAR> autorunFileName(GetAutorunFileName());

    if (autorunFileName.IsNull())
    {
        return FALSE;
    }

    CMyBuffer<WCHAR> processFileName(GetQuotedString(GetCurrentProcessFileName()));

    if (processFileName.IsNull())
    {
        return TRUE;
    }

    if (lstrcmpi(autorunFileName.GetBuffer(), processFileName.GetBuffer()) == 0)
    {
        return TRUE;
    }

    return FALSE;
}

void CMyAppStartup::SetAppStartsWhenWindowsStarts()
{
    CMyBuffer<WCHAR> currentProcessFileName(GetQuotedString(GetCurrentProcessFileName()));

    if (currentProcessFileName.IsNull())
    {
        return;
    }

    DWORD cbData = sizeof(WCHAR) * (lstrlen(currentProcessFileName.GetBuffer()) + 1);
    RegSetKeyValue(HKEY_CURRENT_USER, g_szRegSubKey, g_szRegValueName, REG_SZ, currentProcessFileName.GetBuffer(), cbData);
}

static LPWSTR GetAutorunFileName()
{
    CMyBuffer<WCHAR> result(MAX_PATH + 1);

    DWORD cbData = sizeof(WCHAR) * (MAX_PATH + 1);
    if (RegGetValue(HKEY_CURRENT_USER, g_szRegSubKey, g_szRegValueName, RRF_RT_REG_SZ, NULL, result.GetBuffer(), &cbData) == ERROR_SUCCESS)
    {
        return result.Detach();
    }

    return NULL;
}

static LPWSTR GetQuotedString(LPWSTR lpStr)
{
    if (lpStr == NULL)
    {
        return NULL;
    }

    CMyBuffer<WCHAR> result(lstrlen(lpStr) + 3);

    lstrcpy(result.GetBuffer(), L"\"");
    lstrcat(result.GetBuffer(), lpStr);
    lstrcat(result.GetBuffer(), L"\"");

    return result.Detach();
}
